<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('名称')" maxlength="25" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('编码')" prop="code">
            <el-input v-model="form.code" :placeholder="$t('编码')" maxlength="20" show-word-limit />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">
          <el-form-item :label="$t('连接ID')" prop="joinId">
            <el-input v-model="form.joinId" :placeholder="$t('连接ID')" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('Sql脚本')" prop="sqlScript">
            <textarea ref="sqlScript" v-model="form.sqlScript" class="codesql" style="height:500px;width:600px;" />
          </el-form-item>
        </el-col>-->
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" :placeholder="$t('备注')" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
        <!--        <div class="area-header">
          <span class="area-header-title" style="float: left;">{{ $t('字段列表') }}</span>
          <span style="float: right;font-size: 14px;">
            <template>
              <el-button
                v-hasPermi="['jmf:package:edit']"
                size="mini"
                type="primary"
                @click="getColumnBySql"
              >{{ $t('刷新') }}</el-button>
            </template>
          </span>
        </div>
        <el-table
          v-loading="filedShow"
          :data="form.jmfDataSetFieldList"
          border
          class="nowrapTable formTable"
        >
          <el-table-column :label="$t('字段名称')" align="center">
            <template slot-scope="scope">
              {{ scope.row.code }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段别名')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段别名') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'jmfDataSetFieldList.' + scope.$index + '.label'" :rules="fieldListRules.label">
                <el-input v-model="scope.row.label" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'jmfDataSetFieldList.' + scope.$index + '.type'" :rules="fieldListRules.type">
                <el-select
                  v-model="scope.row.type"
                  :placeholder="$t('请选择')"
                  clearable
                  style="width: 100%"
                  @change="updateFormatValue(scope.row)"
                >
                  <el-option
                    v-for="field in filedTypeOptions"
                    :key="field.dictValue"
                    :label="$t(field.dictLabel)"
                    :value="field.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('是否展示给用户')" align="center" width="150">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isShow"
                active-value="Y"
                inactive-value="N"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('排序')" align="center" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sort" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('默认宽度')" align="center" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.width" />
            </template>
          </el-table-column>
        </el-table>-->
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="jmf:package" />
    </div>
  </div>
</template>

<script>
    import { saveJmfDataPackage, getJmfDataPackage } from '@/api/dev/jmf/jmfDataPackage'
    import { getColumnBySql } from '@/api/system/search/searchSqlBase'
    import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'
    export default {
        data() {
            return {
                // 表单参数
                form: {},
                // 字典列表是否显示
                filedShow: false,
                // 遮罩层
                loading: false,
                editor: undefined,
              filedTypeOptions: [],
              dictOptions: [],
                // 表单校验
                rules: {
                  name: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  code: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  sqlScript: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
              fieldListRules: {
                label: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                type: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
              }
            }
        },
        created() {
          this.getDicts('search_field_type').then(response => {
            this.filedTypeOptions = response.data
          })
          /** 查询字典下拉列表 */
          getDictOptionselect().then(response => {
            this.dictOptions = response.data
          })
        },
      mounted() {
        // const mime = 'text/x-mariadb'
        // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
        /* this.editor = CodeMirror.fromTextArea(this.$refs.sqlScript, {
          mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
          indentWithTabs: true,
          smartIndent: true,
          lineNumbers: true,
          matchBrackets: true,
          // theme: theme,
          autofocus: true,
          extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
          hintOptions: { // 自定义提示选项
            tables: {
              users: ['name', 'score', 'birthDate'],
              countries: ['name', 'population', 'size']
            }
          }
        }) */
       /* this.editor.on('cursorActivity', function() {
          if (this !== null) {
            this.editor.showHint()
          }
        })*/
      },
      methods: {
            // 初始化数据
            init(data) {
                if (data != null && data.id !== undefined) {
                    getJmfDataPackage(data.id).then(response => {
                        this.form = response.data
                        this.editor.setValue(this.form.sqlScript !== null ? this.form.sqlScript : '')
                    })
                } else {
                    this.reset()
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    name: undefined,
                    code: undefined,
                    remark: undefined,
                    createBy: undefined,
                    updateBy: undefined,
                    createTime: undefined,
                    updateTime: undefined,
                    joinId: undefined,
                    jmfDataSetFieldList: []
                }
                // this.editor.setValue('')
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
             // this.form.sqlScript = this.editor.getValue()
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveJmfDataPackage(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
        getColumnBySql: function() {
          // this.form.searchSql = this.editor.getValue()
          if (this.form.searchSql === null || this.form.searchSql === '') {
            this.$message.error('sql脚本不能为空')
          } else {
            getColumnBySql(this.form).then(response => {
              this.filedShow = true
              // 保存之前配置的数据
              var fieldTempMap = {}
              for (var j = 0; j < this.form.jmfDataSetFieldList.length; j++) {
                var filed = this.form.jmfDataSetFieldList[j]
                fieldTempMap[filed.code] = filed
              }
              var jmfDataSetFieldList = []
              for (var i = 0; i < response.data.length; i++) {
                var field = {}
                if (fieldTempMap[response.data[i]] !== null && fieldTempMap[response.data[i]] !== undefined) {
                  field = fieldTempMap[response.data[i]]
                  field.sort = (i + 1) * 10
                } else {
                  field.code = response.data[i]
                  field.label = response.data[i]
                  field.type = 'WB'
                  field.isShow = 'Y'
                  field.sort = (i + 1) * 10
                  field.width = 200
                }
                jmfDataSetFieldList.push(field)
                this.$set(this.form, 'jmfDataSetFieldList', jmfDataSetFieldList)
                this.filedShow = false
              }
            })
          }
        },
        // 设置格式化字段默认值
        updateFormatValue: function(row) {
          if (row.type === 'JE') {
            row.format = '###,###.####'
          } else if (row.type === 'RQ') {
            row.format = 'yyyy-MM-dd'
          }
        }

        }

    }
</script>
